import { Database, db } from "@/api";
import { FormModal, createModalAtom } from "@/components";
import { ResultUtil } from "@/util";
import { useStore } from "@/util/hooks";
import { AutoComplete, Button, Form, Input } from "@arco-design/web-react";
import { DBTableAtom } from "..";

export const DBTableModalAtom = createModalAtom<Database>();

export const DBTableModal = () => {
  const { value, updateStore } = useStore(DBTableModalAtom);
  const dbTableStore = useStore(DBTableAtom);
  const [form] = Form.useForm();

  async function onConfirm() {
    const values = await form.validate();
    let res;
    if (!value.record) {
      res = await db.save({
        ...values,
      });
    } else {
      res = await db.update({
        ...value.record,
        ...values,
      });
    }
    if (ResultUtil.showError(res)) {
      const listRes = await db.list();
      dbTableStore.updateStore({
        data: listRes?.data,
      });
      updateStore({
        open: false,
      });
    }
  }

  async function dbConnectTest() {
    const values = await form.validate();
    const res = await db.connectTest(values);
    ResultUtil.showResult(res);
  }

  return (
    <FormModal
      title="数据源"
      form={form}
      atom={DBTableModalAtom}
      onConfirm={onConfirm}
      footer={(cancelButtonNode, okButtonNode) => {
        return (
          <>
            <Button style={{ marginRight: 40 }} onClick={dbConnectTest}>
              测试
            </Button>
            {cancelButtonNode}
            {okButtonNode}
          </>
        );
      }}
    >
      <Form form={form} labelCol={{ span: 5 }}>
        <Form.Item
          label="名称"
          field="name"
          requiredSymbol={false}
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="JDBC"
          field="url"
          requiredSymbol={false}
          rules={[{ required: true }]}
        >
          <Input placeholder="jdbc:mysql://ip:3306/database?xxx" />
        </Form.Item>
        <Form.Item label="数据库" field="dbName" requiredSymbol={false}>
          <Input style={{ width: 150 }} placeholder="database" />
        </Form.Item>
        <Form.Item
          label="Driver"
          field="driverClassName"
          requiredSymbol={false}
          rules={[{ required: true }]}
        >
          <AutoComplete
            placeholder="如: com.mysql.cj.jdbc.Driver"
            data={[
              "com.mysql.cj.jdbc.Driver",
              "com.mysql.jdbc.Driver",
              "org.postgresql.Driver",
            ]}
          />
        </Form.Item>
        <Form.Item label="用户名" field="username">
          <Input style={{ width: 250 }} />
        </Form.Item>
        <Form.Item label="密码" field="password">
          <Input style={{ width: 250 }} />
        </Form.Item>
      </Form>
    </FormModal>
  );
};
